package com.example.community.provider;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.example.community.util.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

@Service
public class AliyunOssProvider {
    @Value("${aliyun.oss.accessKey}")
    private String accessKey;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;



    public UFileResult upload(InputStream fileInputStream, String mimeType, String objectName){
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey,accessKeySecret);
        UFileResult uFileResult = new UFileResult();
        try {

            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            uFileResult.setFileName(objectName);
            uFileResult.setFileUrl("http://pic.haidacommunity.cn/" + mimeType + "/" + objectName);
            //bucket仓库名/保存文件名,包含路径和文件名/文件的流
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(mimeType);

            PutObjectResult putObjectResult = ossClient.putObject(bucketName, mimeType + "/" + objectName, fileInputStream,objectMetadata);
        }catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        }
        finally {
            if (ossClient != null){
                ossClient.shutdown();
            }
        }
        return uFileResult;
    }


    public UFileResult upload(String url) {
        File newFile = FileUtils.newFile(url);
        assert newFile != null;
        UFileResult fileResult;
        try {
            fileResult = upload(new FileInputStream(newFile), "image/png", newFile.getName());
        } catch (FileNotFoundException e) {
            throw new RuntimeException("new file exception", e);
        }
        FileUtils.deleteFile(newFile);
        return fileResult;
    }
}
